<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="auto" class="login-form" size="small" status-icon>
      <h1 class="title">E S D N</h1>
      <img src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"  class="user-Avater">
      <h4  class="introduction" >让知识传递变得更简单</h4>
      <el-form-item prop="userId"> 
        <el-input
          v-model="loginForm.userId"
          type="text"
          auto-complete="off"
          placeholder="用户名/工号"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
        </el-input>
      </el-form-item>
       <div  class = "findPassword" style="font-size:smaller">
        <router-link  :to="'/findPassword'" >忘记登录密码</router-link>
       </div>
       <el-form-item  style="  font-size: smaller;">
        <el-checkbox v-model="loginForm.rememberMe" >记住我</el-checkbox>
       </el-form-item>
      <el-form-item style="width:100%;">
        <div   style="width:100%;">
          <el-button
          :loading="loading"
          size="medium"
          type="primary"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        </div>
        <div style=" width:100%; height: 50px;margin-top: 20px; padding:10px;">
          <router-link style="float: right;" class="link-type" :to="'/register'">没有账户？立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>ESDN欢迎你的到来</span>
    </div>
  </div>
</template>

<script>
import {postLoginFormData} from "@/api/login/login";
export default {
  name: "login",
  data() {
    return {
      loginForm: {
        userId: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        userId: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  
  methods: { 
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // 记住密码的cookies设置
          if (this.loginForm.rememberMe) {
            this.setCookie(this.loginForm.userId, this.loginForm.password, 30);
          }else{
            this.clearCookie();
          }
          // 提交表单数据处理
          let formData = {
            userId: this.loginForm.userId,
            password: this.loginForm.password
          }
         let data = JSON.stringify(formData);
          console.log(data);
         postLoginFormData(data)
          .then((res) => {
          console.log(res);
          if (res.code!== 200){
            this.loading=false;
             this.$message({
             message: res.msg,
             type: 'warning'
               });
          }else{
             //先清除本地存储
             localStorage.removeItem('userId');
             localStorage.removeItem('avatar');
             localStorage.removeItem('userName');
             localStorage.removeItem('userType');
             localStorage.removeItem('userDept');
            // 获取公共变量并存储
            this.$store.commit("setUserId",this.loginForm.userId)
            this.$store.commit("setAvatar",'data:image/png;base64,'+res.data.avatar)
            this.$store.commit("setUserName",res.data.userName)
            this.$store.commit("setUserType",res.data.userType)
            this.$store.commit("setUserDept",res.data.deptName)
            // 设置本地存储信息
            localStorage.setItem("userId",JSON.stringify(res.data.userId));
            localStorage.setItem("avatar",JSON.stringify('data:image/png;base64,'+res.data.avatar));
            localStorage.setItem("userName",JSON.stringify(res.data.userName));
            localStorage.setItem("userType",JSON.stringify(res.data.userType));
            localStorage.setItem("userDept",JSON.stringify(res.data.deptName));
            // 路由跳转
            this.$router.push('/home');
          }

         }).catch(() => {
            this.loading = false;
          });
        }
      });
    },
    setCookie(userId, password, exdays) {
      var exdate = new Date(); // 获取当前登录的时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); // 将当前登录的时间加上七天，就是cookie过期的时间，也就是保存的天数
      // 字符串拼接cookie,因为cookie存储的形式是name=value的形式
      window.document.cookie = "userId" + "=" + userId + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie = "password" + "=" + password + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie = "rememberMe" + "=" + this.loginForm.rememberMe + ";path=/;expires=" + exdate.toGMTString();
    },
    getCookie () {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //因为是数组所以要切割。
        // console.log(arr,"切割");
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); // 再次切割
          // console.log(arr2,"切割2");
          // // 判断查找相对应的值
          if (arr2[0] === "userId") {
            this.loginForm.userId = arr2[1]; // 转存一份保存用户名和密码
          } else if (arr2[0] === "password") {
            this.loginForm.password = arr2[1];//可解密
          } else if (arr2[0] === "rememberMe") {
            this.loginForm.rememberMe = Boolean(arr2[1]);
          }
        }
      }
    },
     // 清除cookie
     clearCookie(){
      this.setCookie("", "", -1); // 清空并设置天数为负1天
    },

    },
   mounted() {
    // 第1步，在页面加载的时候，首先去查看一下cookie中有没有用户名和密码可以用
    this.getCookie();
  },
  };
</script>

<style  scoped>

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top:50px;
  height: 100%;
  background-size: cover;
}
.title {
  margin: 0px auto 20px auto;
  text-align: center;
  color: black;
}
a {
  text-decoration: none;
  color:rgb(2, 167, 240);
}
.user-Avater {
   display: block;
   margin: 10px  auto;
   border-radius : 50%;
   height:80px;
   width:80px;   
}
.introduction {
    margin: 10px auto 30px auto;
    text-align: center;
    color: rgb(85, 85, 85);
}
.login-form {
  border-radius: 15px;
  border: 1px solid  rgb(85, 85, 85);
  width: 400px;
  text-align: center;
  font-size: 15px;
  padding: 25px 25px 25px 25px;
 
}
 .el-button {
       display:block;
        width:120px;
        height:35px; 
        margin:0 auto; 
        border-radius: 5px;
        background-color: rgb(2, 167, 240); 
        color: #fefefe; 
        border: 2px solid #A9A9A9;
  }
 .el-input {
    width:70%;  
  }
.el-checkbox {
     display:block; 
     margin-left:45px;
     margin-top:0px;  
     width:100px; 
     font-size:smaller; 
  }
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 10px;
  float: right;
}
img {
    cursor: pointer;
    vertical-align: middle;
  }
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: black;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
 
 <style>
 .el-form-item__error {
    margin-left:60px;
 }
 </style>